const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { verifyToken, checkRolePermission } = require('./auth');

// 获取用户权限列表和菜单
router.get('/getUserPermissionList', verifyToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户的角色
    const [userRoles] = await pool.execute(`
      SELECT r.id, r.code
      FROM roles r
      INNER JOIN user_roles ur ON r.id = ur.role_id
      WHERE ur.user_id = ?
    `, [userId]);
    
    if (userRoles.length === 0) {
      return res.json({
        code: 200,
        message: '获取用户权限成功',
        data: {
          permissions: [],
          menus: []
        }
      });
    }
    
    // 获取角色的菜单权限
    const roleIds = userRoles.map(role => role.id);
    const rolePlaceholders = roleIds.map(() => '?').join(',');
    
    // 获取角色有权限的所有菜单项 (包括按钮权限)
    const [menusWithPermissions] = await pool.execute(`
      SELECT DISTINCT m.*
      FROM menus m
      INNER JOIN role_menus rm ON m.id = rm.menu_id
      WHERE rm.role_id IN (${rolePlaceholders})
      ORDER BY m.sort ASC
    `, roleIds);
    
    // 获取所有菜单项用于查找父级菜单
    const [allMenus] = await pool.execute(`SELECT * FROM menus`);
    
    // 创建一个包含用户所有权限及其父级菜单的集合
    const menuSet = new Set();
    const permissionCodes = [];
    
    // 添加直接授权的菜单和权限
    menusWithPermissions.forEach(menu => {
      menuSet.add(menu.id);
      if (menu.permission_code) {
        permissionCodes.push(menu.permission_code);
      }
    });
    
    // 添加所有父级菜单
    const addParentMenus = (menuId) => {
      const menu = allMenus.find(m => m.id === menuId);
      if (menu && menu.parent_id && menu.parent_id !== 0) {
        menuSet.add(menu.parent_id);
        // 递归添加更高层级的父菜单
        addParentMenus(menu.parent_id);
      }
    };
    
    // 为每个授权菜单添加其父级菜单
    menusWithPermissions.forEach(menu => {
      if (menu.parent_id && menu.parent_id !== 0) {
        addParentMenus(menu.parent_id);
      }
    });
    
    // 获取完整的菜单列表（包括所有必要的父级菜单）
    const completeMenuItems = allMenus.filter(menu => 
      (menuSet.has(menu.id) || menuSet.has(menu.parent_id)) && menu.type === 'menu'
    );
    
    // 构建树形菜单结构
    const menuTree = buildMenuTree(completeMenuItems);
    
    res.json({
      code: 200,
      message: '获取用户权限成功',
      data: {
        permissions: permissionCodes,
        menus: menuTree
      }
    });
  } catch (error) {
    console.error('获取用户权限错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 获取用户信息及角色
router.get('/getUserInfo', verifyToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 查询用户信息
    const [users] = await pool.execute(
      'SELECT id, username, name, email FROM users WHERE id = ?', 
      [userId]
    );
    
    if (users.length === 0) {
      return res.status(404).json({ 
        code: 404, 
        message: '用户不存在' 
      });
    }
    
    // 获取用户角色
    const [roles] = await pool.execute(`
      SELECT r.id, r.name, r.code 
      FROM roles r
      INNER JOIN user_roles ur ON r.id = ur.role_id
      WHERE ur.user_id = ?
    `, [userId]);
    
    const user = users[0];
    user.roles = roles;
    
    res.json({
      code: 200,
      message: '获取用户信息成功',
      data: user
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 获取用户菜单列表
router.get('/getUserMenus', verifyToken, async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 获取用户的角色
    const [userRoles] = await pool.execute(`
      SELECT r.id, r.code
      FROM roles r
      INNER JOIN user_roles ur ON r.id = ur.role_id
      WHERE ur.user_id = ?
    `, [userId]);
    
    if (userRoles.length === 0) {
      return res.json({
        code: 200,
        message: '获取菜单成功',
        data: []
      });
    }
    
    const roleIds = userRoles.map(role => role.id);
    let menus = [];
    
    // 如果用户是管理员，获取所有菜单
    if (userRoles.some(role => role.code === 'admin')) {
      [menus] = await pool.execute(`
        SELECT * FROM menus ORDER BY sort ASC
      `);
    } else {
      // 非管理员，根据权限获取菜单
      const rolePlaceholders = roleIds.map(() => '?').join(',');
      
      // 先获取用户角色的所有权限
      const [permissions] = await pool.execute(`
        SELECT DISTINCT p.id
        FROM permissions p
        INNER JOIN role_permissions rp ON p.id = rp.permission_id
        WHERE rp.role_id IN (${rolePlaceholders})
      `, roleIds);
      
      if (permissions.length === 0) {
        return res.json({
          code: 200,
          message: '获取菜单成功',
          data: []
        });
      }
      
      // 根据权限获取菜单
      const permissionIds = permissions.map(p => p.id);
      const permPlaceholders = permissionIds.map(() => '?').join(',');
      
      // 获取有权限的菜单ID
      const [menuIds] = await pool.execute(`
        SELECT DISTINCT menu_id 
        FROM menu_permissions 
        WHERE permission_id IN (${permPlaceholders})
      `, permissionIds);
      
      if (menuIds.length === 0) {
        // 获取不需要权限的菜单(不在menu_permissions表中的菜单)
        [menus] = await pool.execute(`
          SELECT * 
          FROM menus 
          WHERE id NOT IN (
            SELECT DISTINCT menu_id FROM menu_permissions
          )
          ORDER BY sort ASC
        `);
      } else {
        // 获取有权限的菜单 + 不需要权限的菜单
        const menuIdList = menuIds.map(m => m.menu_id);
        const menuPlaceholders = menuIdList.map(() => '?').join(',');
        
        [menus] = await pool.execute(`
          SELECT * 
          FROM menus 
          WHERE id IN (${menuPlaceholders})
          OR id NOT IN (
            SELECT DISTINCT menu_id FROM menu_permissions
          )
          ORDER BY sort ASC
        `, menuIdList);
      }
    }
    
    // 构建树形菜单结构
    const menuTree = buildMenuTree(menus);
    
    res.json({
      code: 200,
      message: '获取菜单成功',
      data: menuTree
    });
  } catch (error) {
    console.error('获取菜单错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 获取角色列表
router.get('/getRoleList', verifyToken, checkRolePermission('role:read'), async (req, res) => {
  try {
    // 获取查询参数
    const { page = 1, pageSize = 10, name, code, description, sortField = 'id', sortOrder = 'asc' } = req.query;
    
    // 构建查询条件
    let whereClause = '';
    const params = [];
    const conditions = [];
    
    if (name) {
      conditions.push('name LIKE ?');
      params.push(`%${name}%`);
    }
    
    if (code) {
      conditions.push('code LIKE ?');
      params.push(`%${code}%`);
    }
    
    if (description) {
      conditions.push('description LIKE ?');
      params.push(`%${description}%`);
    }
    
    if (conditions.length > 0) {
      whereClause = `WHERE ${conditions.join(' AND ')}`;
    }
    
    // 排序
    const orderClause = `ORDER BY ${sortField} ${sortOrder === 'desc' ? 'DESC' : 'ASC'}`;
    
    // 查询总数
    const [countResult] = await pool.execute(`
      SELECT COUNT(*) as total
      FROM roles
      ${whereClause}
    `, params);
    
    const total = countResult[0].total;
    
    // 如果不需要分页（pageSize为0），则返回所有数据
    if (parseInt(pageSize) === 0) {
      const [roles] = await pool.execute(`
        SELECT id, name, code, description, created_at, updated_at
        FROM roles
        ${whereClause}
        ${orderClause}
      `, params);
      
      return res.json({
        code: 200,
        message: '获取角色列表成功',
        data: roles
      });
    }
    
    // 计算分页参数
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);
    
    // 执行分页查询 - 在SQL字符串中直接使用数值而不是参数占位符
    const [roles] = await pool.execute(`
      SELECT id, name, code, description, created_at, updated_at
      FROM roles
      ${whereClause}
      ${orderClause}
      LIMIT ${offset}, ${limit}
    `, params);
    
    res.json({
      code: 200,
      message: '获取角色列表成功',
      data: {
        list: roles,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
        total
      }
    });
  } catch (error) {
    console.error('获取角色列表错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 获取权限列表
router.get('/getPermissionList', verifyToken, checkRolePermission('permission:read'), async (req, res) => {
  try {
    const [permissions] = await pool.execute(`
      SELECT id, name, title, type, permission_code, parent_id, created_at
      FROM menus
      ORDER BY created_at
    `);
    
    res.json({
      code: 200,
      message: '获取权限列表成功',
      data: permissions
    });
  } catch (error) {
    console.error('获取权限列表错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 获取所有菜单列表 (需要管理员权限)
router.get('/getMenuList', verifyToken, checkRolePermission('system:menu:view'), async (req, res) => {
  try {
    const [menus] = await pool.execute('SELECT * FROM menus ORDER BY sort ASC');
    
    const menuTree = buildMenuTree(menus);
    
    res.json({
      code: 200,
      message: '获取菜单列表成功',
      data: menuTree
    });
  } catch (error) {
    console.error('获取菜单列表错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 获取用户列表
router.get('/getUserList', verifyToken, checkRolePermission('system:user:view'), async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const pageSize = parseInt(req.query.pageSize) || 10;
    const offset = (page - 1) * pageSize;
    const query = req.query.query || '';
    
    // 构建查询条件
    let queryCondition = '';
    let queryParams = [];
    
    if (query) {
      queryCondition = 'WHERE username LIKE ? OR name LIKE ? OR email LIKE ?';
      queryParams = [`%${query}%`, `%${query}%`, `%${query}%`];
    }
    
    // 查询总数
    const [countResult] = await pool.execute(`
      SELECT COUNT(*) as total FROM users ${queryCondition}
    `, queryParams);
    
    const total = countResult[0].total;
    
    // 查询用户数据 - 直接在SQL中插入LIMIT和OFFSET值
    const [users] = await pool.execute(`
      SELECT id, username, name, email, created_at, updated_at
      FROM users ${queryCondition}
      ORDER BY id DESC
      LIMIT ${parseInt(pageSize)} OFFSET ${parseInt(offset)}
    `, queryParams);
    
    // 查询用户角色
    const userList = await Promise.all(users.map(async (user) => {
      const [roles] = await pool.execute(`
        SELECT r.id, r.name, r.code 
        FROM roles r
        INNER JOIN user_roles ur ON r.id = ur.role_id
        WHERE ur.user_id = ?
      `, [user.id]);
      
      return { ...user, roles };
    }));
    
    res.json({
      code: 200,
      message: '获取用户列表成功',
      data: {
        list: userList,
        total,
        page,
        pageSize
      }
    });
  } catch (error) {
    console.error('获取用户列表错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 添加用户
router.post('/addUser', verifyToken, checkRolePermission('user:add'), async (req, res) => {
  try {
    const { username, password, name, email } = req.body;
    
    // 验证必填字段
    if (!username || !password || !name) {
      return res.status(400).json({
        code: 400,
        message: '用户名、密码和姓名为必填字段'
      });
    }
    
    // 检查用户名是否已存在
    const [existingUsers] = await pool.execute('SELECT id FROM users WHERE username = ?', [username]);
    if (existingUsers.length > 0) {
      return res.status(400).json({
        code: 400,
        message: '用户名已存在'
      });
    }
    
    // 创建用户
    const [result] = await pool.execute(`
      INSERT INTO users (username, password, name, email, created_at, updated_at)
      VALUES (?, ?, ?, ?, NOW(), NOW())
    `, [username, password, name, email || null]);
    
    res.json({
      code: 200,
      message: '添加用户成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('添加用户错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 更新用户
router.post('/updateUser', verifyToken, checkRolePermission('system:user:edit'), async (req, res) => {
  try {
    const { id, name, email, password } = req.body;
    
    // 验证必填字段
    if (!id || !name) {
      return res.status(400).json({
        code: 400,
        message: 'ID和姓名为必填字段'
      });
    }
    
    // 检查用户是否存在
    const [existingUsers] = await pool.execute('SELECT id FROM users WHERE id = ?', [id]);
    if (existingUsers.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 构建更新字段
    let updateFields = [];
    let updateParams = [];
    
    updateFields.push('name = ?');
    updateParams.push(name);
    
    updateFields.push('email = ?');
    updateParams.push(email || null);
    
    if (password) {
      updateFields.push('password = ?');
      updateParams.push(password);
    }
    
    updateFields.push('updated_at = NOW()');
    
    // 执行更新
    await pool.execute(`
      UPDATE users SET ${updateFields.join(', ')} WHERE id = ?
    `, [...updateParams, id]);
    
    res.json({
      code: 200,
      message: '更新用户成功'
    });
  } catch (error) {
    console.error('更新用户错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 删除用户
router.post('/deleteUser', verifyToken, checkRolePermission('user:delete'), async (req, res) => {
  try {
    const { id } = req.body;
    
    // 验证必填字段
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '用户ID为必填字段'
      });
    }
    
    // 检查用户是否存在
    const [existingUsers] = await pool.execute('SELECT id FROM users WHERE id = ?', [id]);
    if (existingUsers.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 删除用户角色关联
      await connection.execute('DELETE FROM user_roles WHERE user_id = ?', [id]);
      
      // 删除用户
      await connection.execute('DELETE FROM users WHERE id = ?', [id]);
      
      // 提交事务
      await connection.commit();
      
      res.json({
        code: 200,
        message: '删除用户成功'
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 分配用户角色
router.post('/assignUserRoles', verifyToken, checkRolePermission('user:assignRole'), async (req, res) => {
  try {
    const { userId, roleIds } = req.body;
    
    // 验证必填字段
    if (!userId || !Array.isArray(roleIds)) {
      return res.status(400).json({
        code: 400,
        message: '用户ID和角色ID数组为必填字段'
      });
    }
    
    // 检查用户是否存在
    const [existingUsers] = await pool.execute('SELECT id FROM users WHERE id = ?', [userId]);
    if (existingUsers.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '用户不存在'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 先删除所有现有角色
      await connection.execute('DELETE FROM user_roles WHERE user_id = ?', [userId]);
      
      // 添加新角色
      if (roleIds.length > 0) {
        const values = roleIds.map(roleId => `(${userId}, ${parseInt(roleId)})`).join(', ');
        await connection.execute(`
          INSERT INTO user_roles (user_id, role_id) VALUES ${values}
        `);
      }
      
      // 提交事务
      await connection.commit();
      
      res.json({
        code: 200,
        message: '分配角色成功'
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('分配角色错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 辅助函数：构建树形菜单
function buildMenuTree(menus, parentId = 0) {
  const result = [];
  
  for (const menu of menus) {
    if (menu.parent_id === parentId) {
      const children = buildMenuTree(menus, menu.id);
      
      if (children.length > 0) {
        menu.children = children;
      }
      
      result.push(menu);
    }
  }
  
  return result;
}

// 添加角色
router.post('/addRole', verifyToken, checkRolePermission('role:add'), async (req, res) => {
  try {
    const { name, code, description } = req.body;
    
    // 验证必填字段
    if (!name || !code) {
      return res.status(400).json({
        code: 400,
        message: '角色名称和编码为必填字段'
      });
    }
    
    // 检查角色编码是否已存在
    const [existingRoles] = await pool.execute('SELECT id FROM roles WHERE code = ?', [code]);
    if (existingRoles.length > 0) {
      return res.status(400).json({
        code: 400,
        message: '角色编码已存在'
      });
    }
    
    // 创建角色
    const [result] = await pool.execute(`
      INSERT INTO roles (name, code, description, created_at, updated_at)
      VALUES (?, ?, ?, NOW(), NOW())
    `, [name, code, description || null]);
    
    res.json({
      code: 200,
      message: '添加角色成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('添加角色错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 更新角色
router.post('/updateRole', verifyToken, checkRolePermission('role:update'), async (req, res) => {
  try {
    const { id, name, description } = req.body;
    
    // 验证必填字段
    if (!id || !name) {
      return res.status(400).json({
        code: 400,
        message: 'ID和角色名称为必填字段'
      });
    }
    
    // 检查角色是否存在
    const [existingRoles] = await pool.execute('SELECT id FROM roles WHERE id = ?', [id]);
    if (existingRoles.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '角色不存在'
      });
    }
    
    // 执行更新
    await pool.execute(`
      UPDATE roles 
      SET name = ?, description = ?, updated_at = NOW()
      WHERE id = ?
    `, [name, description || null, id]);
    
    res.json({
      code: 200,
      message: '更新角色成功'
    });
  } catch (error) {
    console.error('更新角色错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 删除角色
router.post('/deleteRole', verifyToken, checkRolePermission('role:delete'), async (req, res) => {
  try {
    const { id } = req.body;
    
    // 验证必填字段
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '角色ID为必填字段'
      });
    }
    
    // 检查角色是否存在
    const [existingRoles] = await pool.execute('SELECT id FROM roles WHERE id = ?', [id]);
    if (existingRoles.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '角色不存在'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 删除角色权限关联
      await connection.execute('DELETE FROM role_menus WHERE role_id = ?', [id]);
      
      // 删除用户角色关联
      await connection.execute('DELETE FROM user_roles WHERE role_id = ?', [id]);
      
      // 删除角色
      await connection.execute('DELETE FROM roles WHERE id = ?', [id]);
      
      // 提交事务
      await connection.commit();
      
      res.json({
        code: 200,
        message: '删除角色成功'
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('删除角色错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 根据角色ID获取权限
router.get('/getPermissionsByRoleId', verifyToken, checkRolePermission('system:role:view'), async (req, res) => {
  try {
    const { roleId } = req.query;
    // 验证必填字段
    if (!roleId) {
      return res.status(400).json({
        code: 400,
        message: '角色ID为必填字段'
      });
    }
    
    // 查询角色权限
    const [menus] = await pool.execute(`
      SELECT m.id, m.name, m.title, m.type, m.permission_code, m.parent_id
      FROM menus m
      INNER JOIN role_menus rm ON m.id = rm.menu_id
      WHERE rm.role_id = ?
      ORDER BY m.sort ASC
    `, [roleId]);
 
    res.json({
      code: 200,
      message: '获取角色权限成功',
      data: menus
    });
  } catch (error) {
    console.error('获取角色权限错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 分配角色权限
router.post('/assignRolePermissions', verifyToken, checkRolePermission('system:role:permission'), async (req, res) => {
  try {
    const { roleId, menuIds } = req.body;
    
    // 验证必填字段
    if (!roleId || !Array.isArray(menuIds)) {
      return res.status(400).json({
        code: 400,
        message: '角色ID和菜单ID数组为必填字段'
      });
    }
    
    // 检查角色是否存在
    const [existingRoles] = await pool.execute('SELECT id FROM roles WHERE id = ?', [roleId]);
    if (existingRoles.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '角色不存在'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 先删除所有现有权限
      await connection.execute('DELETE FROM role_menus WHERE role_id = ?', [roleId]);
      
      // 添加新权限
      if (menuIds.length > 0) {
        // 过滤和验证menuIds，确保每个ID都是有效的数字
        const validMenuIds = menuIds
          .filter(id => id !== null && id !== undefined && !isNaN(id))
          .map(id => parseInt(id, 10))
          .filter(id => !isNaN(id));
        
        if (validMenuIds.length > 0) {
          // 使用参数占位符方式，而不是字符串拼接，防止SQL注入
          const placeholders = validMenuIds.map(() => '(?, ?)').join(', ');
          const params = [];
          
          validMenuIds.forEach(menuId => {
            params.push(roleId, menuId);
          });
          
          await connection.execute(`
            INSERT INTO role_menus (role_id, menu_id) VALUES ${placeholders}
          `, params);
        }
      }
      
      // 提交事务
      await connection.commit();
      
      res.json({
        code: 200,
        message: '分配权限成功'
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('分配权限错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 添加菜单
router.post('/addMenu', verifyToken, checkRolePermission('system:menu:add'), async (req, res) => {
  try {
    const { 
      parent_id = 0, 
      title, 
      name, 
      path, 
      component, 
      redirect, 
      icon, 
      type = 'menu',
      permission_code,
      sort = 0,
      hidden = 0,
      always_show = 0,
      keep_alive = 0
    } = req.body;
    
    // 验证必填字段
    if (!title || !name) {
      return res.status(400).json({
        code: 400,
        message: '菜单标题和名称为必填字段'
      });
    }
    
    // 验证菜单类型
    if (type !== 'menu' && type !== 'button') {
      return res.status(400).json({
        code: 400,
        message: '菜单类型必须是 menu 或 button'
      });
    }
    
    // 如果是页面菜单，path 是必填的
    if (type === 'menu' && !path) {
      return res.status(400).json({
        code: 400,
        message: '菜单类型为menu时，路径为必填字段'
      });
    }
    
    // 按钮类型必须有权限码
    if (type === 'button' && !permission_code) {
      return res.status(400).json({
        code: 400,
        message: '按钮类型必须指定权限标识'
      });
    }
    
    // 创建菜单
    const [result] = await pool.execute(`
      INSERT INTO menus (
        parent_id, title, name, path, component, redirect, 
        icon, type, permission_code, sort, hidden, always_show, keep_alive, created_at, updated_at
      )
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    `, [
      parent_id, title, name, path || null, component || null, redirect || null, 
      icon || null, type, permission_code || null, sort, hidden, always_show, keep_alive
    ]);
    
    res.json({
      code: 200,
      message: '添加菜单成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('添加菜单错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 更新菜单
router.post('/updateMenu', verifyToken, checkRolePermission('system:menu:edit'), async (req, res) => {
  try {
    const { 
      id, 
      parent_id, 
      title, 
      name, 
      path, 
      component, 
      redirect, 
      icon, 
      type,
      permission_code,
      sort,
      hidden,
      always_show,
      keep_alive
    } = req.body;
    
    // 验证必填字段
    if (!id || !title || !name) {
      return res.status(400).json({
        code: 400,
        message: 'ID、菜单标题和名称为必填字段'
      });
    }
    
    // 验证菜单类型
    if (type !== 'menu' && type !== 'button') {
      return res.status(400).json({
        code: 400,
        message: '菜单类型必须是 menu 或 button'
      });
    }
    
    // 如果是页面菜单，path 是必填的
    if (type === 'menu' && !path) {
      return res.status(400).json({
        code: 400,
        message: '菜单类型为menu时，路径为必填字段'
      });
    }
    
    // 按钮类型必须有权限码
    if (type === 'button' && !permission_code) {
      return res.status(400).json({
        code: 400,
        message: '按钮类型必须指定权限标识'
      });
    }
    
    // 检查菜单是否存在
    const [existingMenus] = await pool.execute('SELECT id FROM menus WHERE id = ?', [id]);
    if (existingMenus.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '菜单不存在'
      });
    }
    
    // 执行更新
    await pool.execute(`
      UPDATE menus 
      SET 
        parent_id = ?, 
        title = ?, 
        name = ?, 
        path = ?, 
        component = ?, 
        redirect = ?, 
        icon = ?, 
        type = ?,
        permission_code = ?,
        sort = ?,
        hidden = ?,
        always_show = ?,
        keep_alive = ?,
        updated_at = NOW()
      WHERE id = ?
    `, [
      parent_id, title, name, path || null, component || null, redirect || null, 
      icon || null, type, permission_code || null, sort, hidden, always_show, keep_alive, id
    ]);
    
    res.json({
      code: 200,
      message: '更新菜单成功'
    });
  } catch (error) {
    console.error('更新菜单错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

// 删除菜单
router.post('/deleteMenu', verifyToken, checkRolePermission('system:menu:delete'), async (req, res) => {
  try {
    const { id } = req.body;
    
    // 验证必填字段
    if (!id) {
      return res.status(400).json({
        code: 400,
        message: '菜单ID为必填字段'
      });
    }
    
    // 检查菜单是否存在
    const [existingMenus] = await pool.execute('SELECT id FROM menus WHERE id = ?', [id]);
    if (existingMenus.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '菜单不存在'
      });
    }
    
    // 检查是否有子菜单
    const [childMenus] = await pool.execute('SELECT id FROM menus WHERE parent_id = ?', [id]);
    if (childMenus.length > 0) {
      return res.status(400).json({
        code: 400,
        message: '请先删除所有子菜单'
      });
    }
    
    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 删除角色菜单关联
      await connection.execute('DELETE FROM role_menus WHERE menu_id = ?', [id]);
      
      // 删除菜单
      await connection.execute('DELETE FROM menus WHERE id = ?', [id]);
      
      // 提交事务
      await connection.commit();
      
      res.json({
        code: 200,
        message: '删除菜单成功'
      });
    } catch (error) {
      // 回滚事务
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  } catch (error) {
    console.error('删除菜单错误:', error);
    res.status(500).json({ 
      code: 500, 
      message: '服务器内部错误' 
    });
  }
});

module.exports = router; 